package org.clipjoint.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.clipjoint.vo.WangEditorImageResult;
import org.clipjoint.vo.WangEditorVideoResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * WangEditor富文本编辑器接口
 *
 * @author 陈光耀
 * date: 2021-1-11
 */
@WebServlet("/wangEditor")
public class WangEditorController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public static Map<String, String> urlAndObjectNameMap = Collections.synchronizedMap(new HashMap<>());

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        switch (method) {
            case "imageUpload":
                imageUpload(request, response);
                break;
            case "videoUpload":
                videoUpload(request, response);
                break;
        }

    }

    // 视频上传接口
    private void videoUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 1.创建磁盘文件项工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 2.创建一个servlet文件上传处理对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        // 3.解析request对象
        List<FileItem> fileItems = new ArrayList<>();
        try {
            fileItems = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 4.遍历判断是否是普通表单字段
        WangEditorVideoResult result = WangEditorVideoResult.builder().errno(0).data(new HashMap<>()).build();
        for (FileItem fileItem : fileItems) {
            if (!fileItem.isFormField()) {
                // 获取文件名
                String fileName = fileItem.getName();
                if (StringUtils.isBlank(fileName)) {
                    continue;
                }

                // 获取webapp下目录的真实路径
                String realPath = request.getServletContext().getRealPath("upload");

                // 生成随机文件名用于保存
                String saveName = UUID.randomUUID().toString() + "-" + fileName;

                try {
                    // 将文件写出到本地
                    fileItem.write(new File(realPath + File.separator + saveName));
                    // 将图片地址存入响应vo
                    result.getData().put("url", request.getContextPath() + File.separator + "upload" + File.separator + saveName);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        // 5.将结果格式化json字符串写回
        response.getWriter().print(JSON.toJSONString(result));

    }

    // 图片上传接口
    private void imageUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        HttpSession session = request.getSession();

        // 1.创建磁盘文件项工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 2.创建一个servlet文件上传处理对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        // 3.解析request对象
        List<FileItem> fileItems = new ArrayList<>();
        try {
            fileItems = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 4.遍历判断是否是普通表单字段
        WangEditorImageResult result = WangEditorImageResult.builder().errno(0).data(new ArrayList<>()).build();
        for (FileItem fileItem : fileItems) {
            if (!fileItem.isFormField()) {
                // 获取文件名
                String fileName = fileItem.getName();
                if (StringUtils.isBlank(fileName)) {
                    continue;
                }

                // 获取webapp下目录的真实路径
                String realPath = request.getServletContext().getRealPath("upload");

                // 生成随机文件名用于保存
                String saveName = UUID.randomUUID().toString() + "-" + fileName;

                try {
                    // 将文件写出到本地
                    fileItem.write(new File(realPath + File.separator + saveName));
                    // 将图片地址存入响应vo
                    result.getData().add(request.getContextPath() + File.separator + "upload" + File.separator + saveName);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }

        // 5.将结果格式化json字符串写回
        response.getWriter().print(JSON.toJSONString(result));

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
